package com.ysxsoft.wdg.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.ysxsoft.wdg.R;

public class ERatingBar extends LinearLayout {
	private int maxRating = 5;
	private boolean canDrag = false;
	private int drawableResouceId;

	public ERatingBar(Context context) {
		this(context, null);
	}

	public ERatingBar(Context context, @Nullable AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public ERatingBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init(context, attrs);
	}

	private void init(Context context, AttributeSet attrs) {
		setWillNotDraw(false);
		setOrientation(HORIZONTAL);
		TypedArray array = context.obtainStyledAttributes(R.styleable.ERatingBar);
		maxRating = array.getInt(R.styleable.ERatingBar_maxRating, 5);
		for (int i = 0; i < maxRating; i++) {
			ImageView imageView = new ImageView(context);
			imageView.setSelected(false);
			imageView.setImageResource(R.drawable.bg_start);
			imageView.setPadding(10, 0, 10, 0);

			imageView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					int p= (int) v.getTag();
					setStar(p+1);
				}
			});
			imageView.setTag(i);
			addView(imageView);
		}
	}

	public void setStar(int p) {
		for (int i = 0; i <getChildCount() ; i++) {
			ImageView imageView= (ImageView) getChildAt(i);
			imageView.setSelected(false);
		}

		for (int i = 0; i < p; i++) {
			ImageView imageView = (ImageView) getChildAt(i);
			if (i <p) {
				imageView.setSelected(true);
			} else {
				imageView.setSelected(false);
			}
		}
		requestLayout();
	}

	public int getStarCount(){
		int count=0;
		for (int i = 0; i <getChildCount() ; i++) {
			ImageView imageView= (ImageView) getChildAt(i);
			if(imageView.isSelected()){
				++count;
			}
		}
		return count;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				break;
			case MotionEvent.ACTION_MOVE:
				if (canDrag) {
				}
				break;
			case MotionEvent.ACTION_UP:
				break;
		}
		return true;
	}
}
